package com.ethan.auth.extention;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author ethan
 * @CreateDate:2022/3/23 14:30
 * @UpdateDate: 2021/6/17 08:52
 * @Version 1.0
 */
@Slf4j
public class SystemGranter extends AbstractTokenGranter {
    /**
     * 授权类型 模拟验证码登录
     */
    private static final String GRANT_TYPE = "admin";
    private final AuthenticationManager authenticationManager;

    public SystemGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                         OAuth2RequestFactory requestFactory
            , AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager =authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String mobile = parameters.get("mobile"); // 手机号
        String code = parameters.get("code"); // 短信验证码
        parameters.remove("code");
        Authentication systemToken = new SystemToken(mobile,code);
        ((SystemToken)systemToken).setDetails(parameters);
        try{
            systemToken =  this.authenticationManager.authenticate(systemToken);
        }catch (Exception e){
            throw new InvalidGrantException("校验异常: " + mobile);
        }
        if (systemToken!=null&&systemToken.isAuthenticated()){
            OAuth2Request storedOAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
            return new OAuth2Authentication(storedOAuth2Request, systemToken);
        }
        throw new InvalidGrantException("无法发现这个用户: " + mobile);
    }

    @Override
    public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {

        return super.grant(grantType, tokenRequest);
    }
}
